package org.edu.modules.research.rbase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.edu.common.base.BasePageDto;
import org.edu.common.base.BaseServiceImpl;
import org.edu.common.utils.ConvertUtils;
import org.edu.common.base.BaseServiceImpl;
import org.edu.modules.research.rbase.entity.VeJkyOrganizeUser;
import org.edu.modules.research.rbase.mapper.VeJkyOrganizeMapper;
import org.edu.modules.research.rbase.entity.VeJkyOrganize;
import org.edu.modules.research.rbase.dto.VeJkyOrganizeDto;
import org.edu.modules.research.rbase.service.VeJkyOrganizeService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import org.edu.modules.research.rbase.service.VeJkyOrganizeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 实现类
 */
@Service
public class VeJkyOrganizeServiceImpl extends BaseServiceImpl<VeJkyOrganize, VeJkyOrganizeMapper> implements VeJkyOrganizeService {

    @Autowired
    public VeJkyOrganizeUserService organizeUserService;

    public IPage<VeJkyOrganizeDto> pageDto(BasePageDto page, @Param(Constants.WRAPPER) Wrapper queryWrapper){
        return mapper.pageDto(page,queryWrapper);
    }
    /**
    * 查询实体类
    */
    public VeJkyOrganizeDto findDtoById(String id) {
        VeJkyOrganize entity = super.findById(id);
        VeJkyOrganizeDto dto = ConvertUtils.convertToDto(entity, VeJkyOrganizeDto.class);

        LambdaQueryWrapper<VeJkyOrganizeUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(VeJkyOrganizeUser::getJkyUserId);
        lambdaQueryWrapper.eq(VeJkyOrganizeUser::getOrgId,dto.getId());
        List<VeJkyOrganizeUser> veJkyOrganizeUsers = organizeUserService.listByWrapper(lambdaQueryWrapper);
        List<Integer> userIds = new ArrayList<>();
        for (VeJkyOrganizeUser user: veJkyOrganizeUsers) {
            userIds.add(user.getJkyUserId());
        }
        dto.setUserIds(userIds);
        return dto;
    }

    /**
    * 新增或者修改
    */
    @Transactional
    public void insertOrUpdate(VeJkyOrganizeDto dto,Boolean isAdd){
        if(isAdd){
            super.insert(dto);
        }else{
            organizeUserService.deleteByOrgId(dto.getId());
            super.update(dto);
        }
        List<VeJkyOrganizeUser> users = new ArrayList<>();
        for (Integer userId:dto.getUserIds()) {
            VeJkyOrganizeUser user = new VeJkyOrganizeUser();
            user.setJkyUserId(userId);
            user.setOrgId(dto.getId());
            users.add(user);
        }
        organizeUserService.insert(users);
    }

}
